home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!news
- From: jlilley@ix.netcom.com (John Lilley)
- Newsgroups: comp.lang.c++
- Subject: Re: Typecasting a class? Help!
- Date: 29 Mar 1996 18:00:24 GMT
- Organization: Netcom
- Message-ID: <4jh8fo$1gp@dfw-ixnews6.ix.netcom.com>
- References: <dkelly.828048898@maestro.inav.net>
- NNTP-Posting-Host: den-co10-17.ix.netcom.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-NETCOM-Date: Fri Mar 29 12:00:24 PM CST 1996
- X-Newsreader: WinVN 0.99.7
-
- In article <dkelly.828048898@maestro.inav.net>, dkelly@blue.weeg.uiowa.edu says...
- >
- >OK, we all know we can do this:
- >
- >x = 6;
- >printf("x is equal to %d\n",x);
- >
- >and it works fine. But what I want to do is this:
- >
- >class MyInt
- >{
- > public:
- > int iTheValue;
- > operator int() { return iTheValue; };
- > void SetValue(int iNewValue) { iTheValue = iNewValue; };
- >};
- >
- >MyInt clInteger;
- >clInteger.SetValue(6);
- >printf("clInteger is equal to %d\n", clInteger);
- >
- >
- >But it doesn't work unless I do this:
- >
- >printf("clInteger is equal to %d\n", (int)clInteger);
- >
- >Is there any way I can get an instance of MyInt to be seen as
- >and integer to printf without having to explicitly cast it as above?
-
- No, since printf uses "..." for the final args, there is no way to
- make the implicit conversion to (int) happen.
-
-
- However, since iostreams have an operator<< that takes an (int)
- as a argument, the implicit conversion to int will takes place
- for "cout << myInt". IMHO, just one of the many advantages to
- iostream vs stdio in the C++ context.
-
- #include <iostream.h>
-
- class MyInt
- {
- public:
- int iTheValue;
- operator int() { return iTheValue; };
- void SetValue(int iNewValue) { iTheValue = iNewValue; };
- };
-
- main()
- {
- MyInt i;
- i.iTheValue = 3;
- cout << i << "\n";
-
- }
-
-
-
-